package com.tif.tiftothumbnail.util;

import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.gce.geotiff.GeoTiffReader;
import org.geotools.image.ImageWorker;
import org.hsqldb.lib.StringUtil;

import javax.imageio.ImageIO;
import javax.media.jai.RenderedOp;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

public class TifThumbnailGenerator {

    /**
     * 生成 TIF 图像的缩略图
     * @param inputFilePath 输入 TIF 图像的文件路径
     * @param outputFilePath 输出缩略图的文件路径
     * @param width 缩略图的宽度
     * @throws IOException 如果读取或写入图像时发生错误
     */
    public static void generateThumbnail(String inputFilePath, String outputFilePath, int width) throws IOException {
        // 读取 TIF 图像
        File inputFile = new File(inputFilePath);
        BufferedImage originalImage = ImageIO.read(inputFile);

        // 获取原始图像的宽度和高度
        int originalWidth = originalImage.getWidth();
        int originalHeight = originalImage.getHeight();

        int targetWidth = width;

        // 根据原图像宽高比计算缩略图的高度
        int height = (int) ((double) originalHeight / originalWidth * targetWidth);

        // 创建缩略图的 BufferedImage 对象
        BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = resizedImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.drawImage(originalImage, 0, 0, width, height, null);
        g2d.dispose();

        // 保存缩略图
        File outputFile = new File(outputFilePath);
        ImageIO.write(resizedImage, "jpg", outputFile);
    }

    public static void generateThumbnailTif(String inputFilePath, String outputFilePath) throws IOException {
        // 读取 TIF 图像
        File inputFile = new File(inputFilePath);

        GeoTiffReader reader = new GeoTiffReader(inputFile);
        GridCoverage2D coverage = reader.read(null);
        BufferedImage  bufferedImage = createThumbnail(coverage);

        // 4. 保存图片
        // 保存缩略图
        File outputFile = new File(outputFilePath);
        ImageIO.write(bufferedImage, "jpg", outputFile);
    }

    public static BufferedImage createThumbnail(GridCoverage2D coverage) {
        // 各波段的最小值和最大值（根据实际情况调整）
        double redMin = 1159, redMax = 1542;
        double greenMin = 1265, greenMax = 1703;
        double blueMin = 1150, blueMax = 1696;

        // 计算缩放参数：scale = 255 / (max - min), offset = -min * scale
        double[][] matrix = {
                {255.0 / (redMax - redMin), 0, 0, -redMin * 255.0 / (redMax - redMin)},
                {0, 255.0 / (greenMax - greenMin), 0, -greenMin * 255.0 / (greenMax - greenMin)},
                {0, 0, 255.0 / (blueMax - blueMin), -blueMin * 255.0 / (blueMax - blueMin)}
        };

        // 应用波段组合操作进行线性拉伸
        RenderedOp scaledImage = new ImageWorker(coverage.getRenderedImage())
                .bandCombine(matrix)
                .getRenderedOperation();

        // 转换为 BufferedImage（TYPE_INT_RGB 类型）
        BufferedImage thumbnail = new BufferedImage(
                scaledImage.getWidth(),
                scaledImage.getHeight(),
                BufferedImage.TYPE_INT_RGB
        );
        thumbnail.setData(scaledImage.getData());

        return thumbnail;
    }


    public synchronized static String method(String filepath, Map<String,String> params){
        String width =  params.get("width");
        if(StringUtil.isEmpty(width)){
            width = "400";
        }
        String outputFilePath =  params.get("outputFilePath");
        if(StringUtil.isEmpty(outputFilePath)){
            outputFilePath = filepath.substring(0,filepath.lastIndexOf("."))+"_"+ Instant.now().getEpochSecond()+".jpg";
        }
        try {
            generateThumbnailTif(filepath, outputFilePath);
            generateThumbnail(outputFilePath, outputFilePath, Integer.parseInt(width));

            System.out.println("缩略图生成成功！");
        } catch (Exception e) {
            System.err.println("生成缩略图时发生错误：" + e.getMessage());
        }
        return outputFilePath;
    }


    public static void main(String[] args) {
        // String inputFilePath = "F:/tif/VH_S1A_IW_GRDH_1SDV_20240629T101956_20240629T102021_054537_06A322_76C3_Orb_tnr_Cal_Spk_TC_dB.tif";
        String inputFilePath = "F:/tif/过火区域1.tif";
        String outputFilePath = "F:/tif/output3.jpg";

//        String inputFilePath1 = "F:/tif/output3.jpg";
//        String outputFilePath2 = "F:/tif/output32.jpg";
//        int width = 400;
//
//        try {
//            generateThumbnailTif(inputFilePath, outputFilePath, width);
//            generateThumbnail(outputFilePath, outputFilePath, width);
//
//            System.out.println("缩略图生成成功！");
//        } catch (Exception e) {
//            System.err.println("生成缩略图时发生错误：" + e.getMessage());
//        }
        Map<String,String> params = new HashMap<>();
        params.put("width","400");
        params.put("outputFilePath",outputFilePath);
        method(inputFilePath,params);




    }
}
